package com.example.batch.core.monitor;

import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.stereotype.Component;
import com.example.batch.core.datasource.DynamicRoutingDataSource;
import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class DataSourceMonitor {

    private final MeterRegistry meterRegistry;
    private final DynamicRoutingDataSource dynamicDataSource;
    
    public DataSourceMonitor(
            MeterRegistry meterRegistry,
            DynamicRoutingDataSource dynamicDataSource) {
        this.meterRegistry = meterRegistry;
        this.dynamicDataSource = dynamicDataSource;
        initMetrics();
    }
    
    private void initMetrics() {
        dynamicDataSource.getResolvedDataSources().forEach((name, dataSource) -> {
            if (dataSource instanceof HikariDataSource) {
                HikariDataSource hikari = (HikariDataSource) dataSource;
                
                Gauge.builder("datasource.connections.active", hikari,
                        this::getActiveConnections)
                    .tag("name", name.toString())
                    .register(meterRegistry);
                    
                Gauge.builder("datasource.connections.max", hikari,
                        this::getMaxConnections)
                    .tag("name", name.toString())
                    .register(meterRegistry);
                    
                // 添加更多监控指标...
            }
        });
    }
    
    private int getActiveConnections(HikariDataSource dataSource) {
        return dataSource.getHikariPoolMXBean().getActiveConnections();
    }
    
    private int getMaxConnections(HikariDataSource dataSource) {
        return dataSource.getMaximumPoolSize();
    }
}
